本文介绍了从项目外部导入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写两个项目,无论是在js。使用Webpack和babel。
我想要创建文件夹 common ,它将包含每个项目中使用的文件。例如一些常数等。



所以我有这样一个结构:

  |  - 项目
| - 服务器
| - config
| - webpack.config.js
| - package.json
| - .babelrc
| - ...
| - 客户端
| - 配置
| - webpack.config.js
| - package.json
| - .babelrc
| - index.js
| - ...
| - common
| - 常量
| - http-codes.js

但是,似乎不可能在项目之外导入文件。例如。在'../common/constants/http-codes.js'中的 client / index.js import *中进行这样的导入是不可能的



你有什么想法可以做这样的进口吗?






更新:



文件:



common / constants / http-codes.js

  export const SUCCESS = 200; 
...






client / index.js

  import'SUCCESS'from'common / constants / HTTP的codes.js'; 
...
console.log(SUCCESS);






client / config / webpack.config.js

  ... 
const PATHS = {
app:path.resolve(__ dirname,'../'),
build:path.resolve(__ dirname,'../build'),
common:path.resolve(__ dirname, ../../common')
};
...
module.exports = {
resolve:{
extensions:['','.js','.jsx','.styl'],
别名:{
...,
common:PATHS.common
}
},
...
}


解决方案

您是否尝试使用nodejs中的路径


I'm writing two projects, both in js. Webpack and babel are used.I want to create folder common which will contain files, that are used in each project. For example some constants etc.

So I have such a structure:

|- project
    |- server
        |- config
           |- webpack.config.js
        |- package.json
        |- .babelrc
        |- ...
    |- client
        |- config
           |- webpack.config.js
        |- package.json
        |- .babelrc
        |- index.js
        |- ...
    |- common
        |- constants
            |- http-codes.js

But, it appeared that it's impossible to import files outside the project. eg. it's impossible to do such an import in client/index.js: import * from '../common/constants/http-codes.js'

Do you have any ideas how such an imports could be done?


Update:

files:

common/constants/http-codes.js:

export const SUCCESS = 200;
...


client/index.js:

import { SUCCESS } from 'common/constants/http-codes.js';
...
console.log(SUCCESS);


client/config/webpack.config.js:

...
const PATHS = {
    app: path.resolve(__dirname, '../'),
    build: path.resolve(__dirname, '../build'),
    common: path.resolve(__dirname, '../../common')
};
...
module.exports = {
    resolve: {
        extensions: [ '', '.js', '.jsx', '.styl' ],
        alias: {
            ...,
            common: PATHS.common
        }
    },
    ...
}
解决方案

Did you try using path module from nodejs?

这篇关于从项目外部导入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 10:53
查看更多